from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from db import models


def depart_list(request):
    # 查询结果是一个列表，每个元素是一个对象，类似java的List<Class>
    departs = models.Department.objects.all()
    return render(request, "depart_list.html", {"departs": departs})


@csrf_exempt
def depart_add(request):
    if request.method == "GET":
        return render(request, "depart_add.html")

    title = request.POST.get("title")
    models.Department.objects.create(title=title)
    return redirect("/depart/list/")


def depart_delete(request):
    did = request.GET.get("did")
    models.Department.objects.filter(id=did).delete()
    return redirect("/depart/list/")


@csrf_exempt
def depart_update(request):
    if request.method == "GET":
        did = request.GET.get("did")
        depart = models.Department.objects.get(id=did)
        return render(request, "depart_update.html", {"depart": depart})
    did = request.POST.get("did")
    title = request.POST.get("title")
    models.Department.objects.filter(id=did).update(title=title)
    return redirect("/depart/list/")


from django.http import JsonResponse


@csrf_exempt
def user_login(request):
    if request.method == "GET":
        return render(request, "user_login.html")
    try:
        user = models.User.objects.get(username=request.POST.get("username"), password=request.POST.get("password"))
    except models.User.DoesNotExist:
        user = None
    if user is not None:
        return JsonResponse({"code": True, "msg": "登录成功！"})
    return JsonResponse({"code": False, "msg": "用户名或密码错误！"})


@csrf_exempt
def stu_list(request):
    if request.method == "GET":
        # 查询结果是一个列表，每个元素是一个对象，类似java的List<Class>
        students = models.Student.objects.all()
        return render(request, "stu_list.html", {"students": students})
    sid = request.POST.get("sid")
    students = models.Student.objects.filter(id=sid)
    return render(request, "stu_list.html", {"students": students})


from django import forms


class StudentModelForm(forms.ModelForm):
    id = forms.CharField(max_length=12, min_length=12, label="学号")

    class Meta:
        model = models.Student
        fields = ["id", "name", "gender", "age", "address", "account", "time", "depart"]
        # widgets = {
        #     "id": forms.TextInput(attrs={"class": "form-control"}),
        #     "name": forms.TextInput(attrs={"class": "form-control"}),
        #
        # }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环，找到所有插件，添加class = form-control的样式
        for name, field in self.fields.items():
            if name == "gender":
                continue
            field.widget.attrs = {'class': 'form-control', "placeholder": field.label}


@csrf_exempt
def stu_add(request):
    if request.method == "GET":
        form = StudentModelForm()
        return render(request, "stu_add.html", {"form": form})

    # 用户POST提交数据,需要进行校验
    form = StudentModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，加入数据库
        # print(form.cleaned_data)
        form.save()
        return redirect("/stu/list/")
    else:
        # 校验失败
        # print(form.errors)
        return render(request, "stu_add.html", {"form": form})


def stu_delete(request):
    sid = request.GET.get("sid")
    models.Student.objects.filter(id=sid).delete()
    return redirect("/stu/list/")


@csrf_exempt
def stu_update(request):
    if request.method == "GET":
        sid = request.GET.get("sid")
        context = {
            'gender_choices': models.Student.gender_choices,
            'departs': models.Department.objects.all(),
            'student': models.Student.objects.get(id=sid)
        }
        return render(request, "stu_update.html", context)
    sid = request.POST.get("sid")
    name = request.POST.get("name")
    gender = request.POST.get("gender")
    depart = request.POST.get("depart")
    models.Student.objects.filter(id=sid).update(name=name,gender=gender,depart=depart)
    return redirect("/stu/list/")


